package com.easylinkin.linkappapi.openapi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.lobar.dto.WorkTypeDTO;
import com.easylinkin.linkappapi.lobar.entity.LaborCompany;
import com.easylinkin.linkappapi.lobar.entity.WorkType;
import com.easylinkin.linkappapi.lobar.entity.emp.EmpUserBase;
import com.easylinkin.linkappapi.lobar.mapper.WorkTypeMapper;
import com.easylinkin.linkappapi.lobar.service.LaborCompanyService;
import com.easylinkin.linkappapi.lobar.util.LobarUtils;
import com.easylinkin.linkappapi.openapi.service.EmpUserBaseService;
import com.easylinkin.linkappapi.openapi.util.IdCardNumberMethod;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

/**
 * @author: kan yuanfeng
 * @Date: 2020/11/04 11:42
 * @Description: 用户花名册管理
 */
@RestController
@RequestMapping("openapi/empUserBase")
@Api(tags = "用户花名册管理")
public class OpenEmpUserBaseController {
  
  @Autowired
  private EmpUserBaseService empUserBaseService;
  @Autowired
  private WorkTypeMapper workTypeMapper;
  @Autowired
  private LaborCompanyService laborCompanyService;

  /**
   * @Description: 增加用户花名册
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping
  @ApiOperation("增加用户花名册")
  public RestMessage insert(@RequestBody EmpUserBase empUserBase){
    //todo 参数验证
    empUserBaseService.insert(empUserBase);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 删除用户花名册（包含批量删除）
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @DeleteMapping
  @ApiOperation("删除用户花名册（包含批量删除）")
  public RestMessage delBatch(@RequestBody EmpUserBase empUserBase){
    Assert.notEmpty(empUserBase.getIds(),"id不能为空");
    empUserBaseService.removeByIds(empUserBase.getIds());
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 编辑用户花名册
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PutMapping
  @ApiOperation("编辑用户花名册")
  public RestMessage updateById(@RequestBody EmpUserBase empUserBase){
    Assert.notNull(empUserBase.getId(),"id不能为空");
    empUserBaseService.updateOne(empUserBase);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 根据id查询用户花名册详情
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("{id}")
  @ApiOperation("根据id查询用户花名册详情")
  public RestMessage findById(@PathVariable("id")String id) {
    Assert.notNull(id,"id不能为空");
    EmpUserBase empUserBase = empUserBaseService.getById(id);
    return RestBuilders.successBuilder().data(empUserBase).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("list")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryListByPage(@RequestBody RequestModel<EmpUserBase> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<EmpUserBase> record =  empUserBaseService.queryListByPage(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }



  //=========================其他辅助接口=====================================
  /**
   * 获取工种数据
   */
  @GetMapping("workType")
  @ApiOperation("获取工种数据")
  public RestMessage getWorkTypeDTOs() {
    QueryWrapper<WorkType> queryWrapper = new QueryWrapper<>();
    queryWrapper.orderByAsc("id");
    List<WorkType> workTypeList = workTypeMapper.selectList(queryWrapper);
    //查询顶级
    List<WorkType> types = workTypeList.stream()
        .filter(w -> Integer.valueOf(0).equals(w.getParentId()))
        .collect(Collectors.toList());
    List<WorkTypeDTO> workTypeDTOS = getWorkTypeDTOs(types);
    getChildren(workTypeList,workTypeDTOS);
    return RestBuilders.successBuilder().data(workTypeDTOS).build();
  }

  /**
   * @Description: 根据条件，查询劳务公司
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("company")
  @ApiOperation("根据条件，查询劳务公司")
  public RestMessage queryCompanyList(){
    List<LaborCompany> companyList =  laborCompanyService.queryCompanyList();
    return RestBuilders.successBuilder().data(companyList).build();
  }

  /**
   * @Description: 根据条件，查询人员库,工种，单位
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("all")
  @ApiOperation("根据条件，查询人员库,工种，单位")
  public Map<String, Object> queryAll(){
    Map<String, Object> map = new HashMap<>();
    //人员
    RequestModel<EmpUserBase> requestModel = new RequestModel<>();
    requestModel.setCustomQueryParams(new EmpUserBase());
    requestModel.setPage(new Page(0,-1));
    IPage<EmpUserBase> record =  empUserBaseService.queryListByPage(requestModel);
    map.put("user",record.getRecords());
    //单位
    List<LaborCompany> companyList =  laborCompanyService.queryCompanyList();
    map.put("company",companyList);
    //工种
    Map<String, String> workTypeMap = LobarUtils.getWorkTypeMap();
    map.put("workType",workTypeMap);
    return map;
  }
//  //调用aep接口保存数据
//  private void insertList(List<User> newUserList, Map<String, String> companyMap) {
//    JSONObject param = new JSONObject();
//    param.put("users",newUserList);
//    param.put("companies",companyMap);
//    RpcEnum.LINKAPP.postForObject("openapi/empUserBase/addList",param,JSONObject.class);
//  }
  /**
   * @Description: 导入花名册
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("insertByExcel")
  @ApiOperation("导入花名册")
  public RestMessage insertOne(@RequestBody JSONObject jsonObject){
    //todo 参数验证
    JSONArray users = jsonObject.getJSONArray("users");
    List<EmpUserBase> empUserBases = users.toJavaList(EmpUserBase.class);
    empUserBases.forEach(e ->{
      try {
        //计算出生日期
        Date birthDay = IdCardNumberMethod.getBirthDayFromIdCard(e.getCard());
        e.setBirthday(birthDay);
        //计算性别
        int sex = IdCardNumberMethod.getSexFromIdCard(e.getCard());
        e.setGender(sex);
        if (StringUtils.isBlank(e.getId())){
          empUserBaseService.insert(e);
        }else {
          empUserBaseService.updateOne(e);
        }
      } catch (Exception exception) {
        exception.printStackTrace();
      }
    });
    Map companies = jsonObject.getObject("companies", Map.class);
    companies.forEach((k,v) ->{
      LaborCompany laborCompany = new LaborCompany();
      laborCompany.setName((String) v);
      laborCompany.setCode((String)k);
      laborCompanyService.insertOne(laborCompany);
    });
    return RestBuilders.successBuilder().build();
  }




  /**
   * 数据转换
   * @param types
   * @return
   */
  private List<WorkTypeDTO> getWorkTypeDTOs(List<WorkType> types) {
    List<WorkTypeDTO> list = new ArrayList<>();
    types.forEach(t ->{
      WorkTypeDTO workTypeDTO = new WorkTypeDTO();
      workTypeDTO.setId(t.getId());
      workTypeDTO.setLabel(t.getName());
      workTypeDTO.setValue(t.getName());
      workTypeDTO.setText(t.getName());
      list.add(workTypeDTO);
    });
    return list;
  }

  /**
   * 设置其子工种
   * @param workTypeList
   * @param types
   */
  private void getChildren(List<WorkType> workTypeList, List<WorkTypeDTO> types) {
    types.forEach(t ->{
      List<WorkType> children = workTypeList.stream().filter(w -> w.getParentId().equals(t.getId()))
          .collect(Collectors.toList());
      if (children.size() > 0){
        List<WorkTypeDTO> workTypeDTOs = getWorkTypeDTOs(children);
        t.setChildren(workTypeDTOs);
        this.getChildren(workTypeList,t.getChildren());
      }
    });
  }
}

